package com.sg.service.biz.component.nb;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.common.util.RedisUtil;
import com.sg.dto.biz.component.req.*;
import com.sg.dto.biz.component.res.*;
import com.sg.service.biz.component.TemplateEngineService;
import com.wicket.okrcomponent.common.baseinfo.BaseInfoDO;
import com.wicket.okrcomponent.common.baseinfo.BaseInfoHolder;
import com.wicket.okrcomponent.common.exception.BizException;
import okhttp3.*;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;


/**
 * @author ： 手工接入方法
 * @version 1.0
 * @since 2022/5/28 15:32
 */
@Service
public class NbMessage {

    private static Map<String, MqttClient> mqttClientPool = new ConcurrentHashMap<>();

    @Resource
    RedisUtil redisUtil;

    @Autowired
    TemplateEngineService templateEngineService;

    /**
     * code:generateSemanticInstance
     * name:M-生成语义实例（特殊方法）
     * desc:undefined
     **/
    @Trace(operationName = "M-生成语义实例（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GenerateSemanticInstanceRespDto generateSemanticInstance(GenerateSemanticInstanceReqDto reqDto) {
        // TODO ruizhe skai dong ; 2022/6/21下午3:15:33
        return new GenerateSemanticInstanceRespDto();
    }

    /**
     * code:sendMobileCaptcha
     * name:M-发送验证码（特殊方法）
     * desc:undefined
     **/
    @Trace(operationName = "M-发送验证码（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddGetCaptchaRespDto addGetCaptcha(AddGetCaptchaReqDto reqDto) {
        // TODO ruizhe skai dong ; 2022/6/21下午3:15:52
        return new AddGetCaptchaRespDto();
    }

    /**
     * code:receptionService
     * name:M2-获取接收字段
     * desc:undefined
     * gen by moon at 8/27/2022, 2:47:33 PM
     **/
    @Trace(operationName = "M2-获取接收字段")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainReceiveFieldsRespDto obtainReceiveFields(ObtainReceiveFieldsReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ObtainReceiveFieldsRespDto.class);
    }

    /**
     * code:receptionService
     * name:M2获取语义对象名称字段
     * desc:undefined
     * gen by moon at 8/27/2022, 5:44:04 PM
     **/
    @Trace(operationName = "M2获取语义对象名称字段")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryFrameInfoCacheRedisDetailRespDto queryFrameInfoCacheRedisDetail(QueryFrameInfoCacheRedisDetailReqDto reqDto) {
        return BeanUtil.toBean(reqDto, QueryFrameInfoCacheRedisDetailRespDto.class);
    }

    /**
     * code:multiCollectionRemoveExistingData
     * name:M2执行数据集相减得结果（特殊方法）
     * desc:undefined
     * gen by moon at 10/1/2022, 11:29:47 PM
     **/
    @Trace(operationName = "M2执行数据集相减得结果（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementDataSetSubtractResultsRespDto implementDataSetSubtractResults(ImplementDataSetSubtractResultsReqDto reqDto) {
        // TODO ruizhe skai dong ; 10/1/2022, 11:29:47 PM
        return new ImplementDataSetSubtractResultsRespDto();
    }


    /**
     * code:obtainChatGptAnswer
     * name:M2获取chatGpt回答
     * desc:undefined
     * gen by moon at 5/28/2023, 12:29:35 AM
     **/
    @Trace(operationName = "M2获取chatGpt回答")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainChatGptAnswerRespDto obtainChatGptAnswer(ObtainChatGptAnswerReqDto reqDto) {
        ObtainChatGptAnswerRespDto retData = new ObtainChatGptAnswerRespDto();
        String URL = "https://api.aigcfun.com/api/v1/text?key=" + reqDto.getCode();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        MessagesDto firstMessage = new MessagesDto();
        firstMessage.setRole("system");
        firstMessage.setContent("请以markdown的形式返回答案");
        reqDto.getMessages().add(0, firstMessage);
        JSONObject reqData = new JSONObject();
        JSONArray jsonArray = JSONArray.parseArray(com.alibaba.fastjson.JSON.toJSONString(reqDto.getMessages()));
        reqData.put("messages", jsonArray);
        reqData.put("model", "gpt-3.5-turbo");
        reqData.put("tokensLength", 500);
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(1000, TimeUnit.SECONDS)
                    .readTimeout(1000, TimeUnit.SECONDS)
                    .build();
            RequestBody body = RequestBody.create(JSON, reqData.toJSONString());
            Request request = new Request.Builder()
                    .url(URL)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {

            }
            String responseBody = response.body().string();
            if (responseBody != null && !responseBody.isEmpty()) {
                JSONObject retJo = JSONObject.parseObject(responseBody);
                JSONArray choicesData = (JSONArray) retJo.get("choices");
                if (choicesData != null && choicesData.size() > 0) {
                    JSONObject textObj = (JSONObject) choicesData.get(0);
                    if (textObj != null) {
                        String retText = textObj.getString("text");
                        retData.setContent(retText);
                        retData.setRole("assistant");
                    }
                }
            }


        } catch (Exception e) {
            System.out.println(e);
        }
        return retData;
    }

    /**
     * code:pushMqttMessageNum
     * name:M2推送mqtt消息数量（特殊方法）
     * desc:undefined
     * gen by moon at 6/3/2023, 8:15:12 PM
     **/
    @Trace(operationName = "M2推送mqtt消息数量（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddMqttMessageNumRespDto addMqttMessageNum(AddMqttMessageNumReqDto reqDto) {
        String broker = reqDto.getWebsocketAgreement() + "://" + reqDto.getWebsocketAddress() + ":" + reqDto.getWebsocketPort();
        String clientId = CommonFunctionHelper.getUid();
//         for(MessageLocationNumDto one : reqDto.getMessageLocationNumList()){
//             if(one.getMessageLocationCode()!=null){
//                 one.setMessageLocationTypeCode(one.getMessageLocationCode());
//             }
//         }
        MqttClient client = null;
        try {
            client = new MqttClient(broker, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setAutomaticReconnect(true);
            options.setCleanSession(true);
            options.setUserName(reqDto.getWebsocketUserId());
            options.setPassword(reqDto.getWebsocketUserPassword().toCharArray());

            boolean connected = false;
            int retryCount = 0;
            int maxRetries = 10; // 设置最大重试次数
            long retryInterval = 1000; // 设置重试间隔时间，单位毫秒

            while (!connected && retryCount < maxRetries) {
                try {
                    client.connect(options);
                    connected = true; // 连接成功
                } catch (MqttException e) {
                    retryCount++;
                    if (retryCount >= maxRetries) {
                        // 达到最大重试次数，抛出异常或其他处理
                        throw e;
                    }
                    // 等待一段时间后重试
                    try {
                        Thread.sleep(retryInterval);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt(); // 恢复中断状态
                    }
                }
            }
//             if(mqttClientPool.containsKey(broker)){
//                 client = mqttClientPool.get(broker);
//                 if(!client.isConnected()){
//                     client = new MqttClient(broker, clientId, new MemoryPersistence());
//                     MqttConnectOptions options = new MqttConnectOptions();
//                     options.setAutomaticReconnect(true);
//                     options.setCleanSession(true);
//                     options.setUserName(reqDto.getWebsocketUserId());
//                     options.setPassword(reqDto.getWebsocketUserPassword().toCharArray());
//
//                     boolean connected = false;
//                     int retryCount = 0;
//                     int maxRetries = 10; // 设置最大重试次数
//                     long retryInterval = 1000; // 设置重试间隔时间，单位毫秒
//
//                     while (!connected && retryCount < maxRetries) {
//                         try {
//                             client.connect(options);
//                             connected = true; // 连接成功
//                             mqttClientPool.put(broker,client);
//                         } catch (MqttException e) {
//                             retryCount++;
//                             if (retryCount >= maxRetries) {
//                                 // 达到最大重试次数，抛出异常或其他处理
//                                 throw e;
//                             }
//                             // 等待一段时间后重试
//                             try {
//                                 Thread.sleep(retryInterval);
//                             } catch (InterruptedException ie) {
//                                 Thread.currentThread().interrupt(); // 恢复中断状态
//                             }
//                         }
//                     }
//                 }
//             }else{
//                 client = new MqttClient(broker, clientId, new MemoryPersistence());
//                 MqttConnectOptions options = new MqttConnectOptions();
//                 options.setAutomaticReconnect(true);
//                 options.setCleanSession(true);
//                 options.setUserName(reqDto.getWebsocketUserId());
//                 options.setPassword(reqDto.getWebsocketUserPassword().toCharArray());
//
//                 boolean connected = false;
//                 int retryCount = 0;
//                 int maxRetries = 10; // 设置最大重试次数
//                 long retryInterval = 1000; // 设置重试间隔时间，单位毫秒
//
//                 while (!connected && retryCount < maxRetries) {
//                     try {
//                         client.connect(options);
//                         connected = true; // 连接成功
//                         mqttClientPool.put(broker,client);
//                     } catch (MqttException e) {
//                         retryCount++;
//                         if (retryCount >= maxRetries) {
//                             // 达到最大重试次数，抛出异常或其他处理
//                             throw e;
//                         }
//                         // 等待一段时间后重试
//                         try {
//                             Thread.sleep(retryInterval);
//                         } catch (InterruptedException ie) {
//                             Thread.currentThread().interrupt(); // 恢复中断状态
//                         }
//                     }
//                 }
//
//
//             }

            MqttClient finalClient = client;
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
//                     System.out.println("Connection lost: " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
//                     System.out.println("Received message: " + new String(message.getPayload()));

                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // Not used in this example
//                     if (finalClient.isConnected()) {
//                         try {
//                             finalClient.disconnect(); // 断开连接
//                             finalClient.close();
//                         } catch (MqttException e) {
//                             e.printStackTrace(); // 打印断开连接时的异常信息
//                         }
//                     }
                }
            });
            JSONObject jo = new JSONObject();
            if (CollectionUtil.isNotEmpty(reqDto.getMessageLocationNumList())) {
                jo.put("messageLocationNumList", reqDto.getMessageLocationNumList());
            }
            if (CollectionUtil.isNotEmpty(reqDto.getRealTimeMonitoringBehaviorInstructionList())) {
                jo.put("realTimeMonitoringBehaviorInstructionList", reqDto.getRealTimeMonitoringBehaviorInstructionList());
            }
            String message = jo.toJSONString();

            MqttMessage msgObject = new MqttMessage(message.getBytes());
            client.publish(reqDto.getMessageTopic(), msgObject);
            client.disconnect();
            client.close();
        } catch (MqttException e) {
            e.printStackTrace();
            redisUtil.set("M2推送mqtt消息数量-报错topic:-" + reqDto.getMessageTopic(), e);
        } finally {
//             if (client.isConnected()) {
//                 try {
//                     client.disconnect(); // 断开连接
//                 } catch (MqttException e) {
//                     e.printStackTrace(); // 打印断开连接时的异常信息
//                 }
//             }
        }

        return new AddMqttMessageNumRespDto();
    }

    /**
     * code:pushMqttChannel
     * name:M2推送mqtt消息通道（特殊方法）
     * desc:undefined
     * gen by moon at 6/3/2023, 8:15:34 PM
     **/
    @Trace(operationName = "M2推送mqtt消息通道（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddMqttMemberChannelRespDto addMqttMemberChannel(AddMqttMemberChannelReqDto reqDto) {
        // TODO ruizhe skai dong ; 6/3/2023, 8:15:34 PM
        return new AddMqttMemberChannelRespDto();
    }

    /**
     * code:pushMqttImportantMessage
     * name:M2推送mqtt强提醒消息（特殊方法）
     * desc:undefined
     * gen by moon at 6/3/2023, 8:15:57 PM
     **/
    @Trace(operationName = "M2推送mqtt强提醒消息（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddMqttUserNoticeRespDto addMqttUserNotice(AddMqttUserNoticeReqDto reqDto) {
        // TODO ruizhe skai dong ; 6/3/2023, 8:15:57 PM
        return new AddMqttUserNoticeRespDto();
    }

    /**
     * code:pushMqttMessage
     * name:M2推送mqtt沟通消息（特殊方法）
     * desc:undefined
     * gen by moon at 6/3/2023, 8:16:19 PM
     **/
    @Trace(operationName = "M2推送mqtt沟通消息（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddMqttMemberMsgReceiveRespDto addMqttMemberMsgReceive(AddMqttMemberMsgReceiveReqDto reqDto) {
        // TODO ruizhe skai dong ; 6/3/2023, 8:16:19 PM
        return new AddMqttMemberMsgReceiveRespDto();
    }

    /**
     * code:subtractionOfTwoNum
     * name:M2计算消息位置当前值减去入参值结果
     * desc:undefined
     * gen by moon at 8/6/2023, 6:15:06 PM
     **/
    @Trace(operationName = "M2计算消息位置当前值减去入参值结果")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public CalculateSubtractOfTwoNumComRespDto calculateSubtractOfTwoNumCom(CalculateSubtractOfTwoNumComReqDto reqDto) {
        CalculateSubtractOfTwoNumComRespDto retData = new CalculateSubtractOfTwoNumComRespDto();
        if (reqDto.getCalcPara1() != null && reqDto.getCalcPara2() != null) {
            BigDecimal result = new BigDecimal(reqDto.getCalcPara1() - reqDto.getCalcPara2());
            retData.setCalcResult(result.doubleValue());
        }
        return retData;
    }

    /**
     * code:dataAppointFormatShiftText
     * name:M2执行数据集按指定格式转文本
     * desc:undefined
     * gen by moon at 9/16/2023, 2:35:39 PM
     **/
    @Trace(operationName = "M2执行数据集按指定格式转文本")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementDataAppointFormatShiftTextRespDto implementDataAppointFormatShiftText(ImplementDataAppointFormatShiftTextReqDto reqDto) {
        if (CollectionUtil.isEmpty(reqDto.getDataAppointFormatShiftTextList())) {
            return new ImplementDataAppointFormatShiftTextRespDto();
        }
        ImplementDataAppointFormatShiftTextRespDto retData = new ImplementDataAppointFormatShiftTextRespDto();
        String result = String.join(reqDto.getCustomField1(), reqDto.getDataAppointFormatShiftTextList());
        retData.setCustomText(result);
        return retData;
    }

    @Trace(operationName = "发生阿里云")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public SendSmsResponse sendAliMsg(SendSmsRequest req, IAcsClient client) {
        try {
            SendSmsResponse ret = client.getAcsResponse(req);
            return ret;
        } catch (ClientException e) {
            throw new BizException("-1", e, false);
        }
    }

    /**
     * code:sendSms
     * name:M2执行发送短信(阿里云类）
     * desc:undefined
     * gen by moon at 9/25/2023, 6:35:08 PM
     **/
    @Trace(operationName = "M2执行发送短信(阿里云类）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementSendSmsRespDto implementSendSms(ImplementSendSmsReqDto reqDto) {
        ImplementSendSmsRespDto retData = new ImplementSendSmsRespDto();
        IClientProfile profile = DefaultProfile.getProfile(reqDto.getSmsServeUrl(), reqDto.getAliyunAk(), reqDto.getAliyunSk());
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsResponse ret = null;
        try {
            // 构建参数
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(reqDto.getSmsReceiver());
            request.setSignName(reqDto.getSmsKey());
            request.setTemplateCode(reqDto.getSmsTemplateCode());
            JSONObject jo = new JSONObject();
            if (reqDto.getIdCardName() != null) {
                jo.put("idCardName", reqDto.getIdCardName());
            }

            if (reqDto.getCycleStandardName() != null) {
                jo.put("cycleStandardName", reqDto.getCycleStandardName());
            }

            if (reqDto.getTargetContentName() != null) {
                jo.put("targetContentName", reqDto.getTargetContentName());
            }
            request.setTemplateParam(jo.toJSONString());
            request.setOutId(CommonFunctionHelper.getUid());
            ret = sendAliMsg(request, client);
            if (ret.getCode() != null && !ret.getCode().equals("OK")) {
                if (ret.getMessage() != null) {
                    throw new BizException("-1", ret.getMessage(), false);
                } else {
                    throw new BizException("-1", "阿里云未知错误", false);
                }

            }
        } catch (Exception e) {
            if (ret.getCode() != null && !ret.getCode().equals("OK")) {
                if (ret.getMessage() != null) {
                    throw new BizException("-1", ret.getMessage(), false);
                } else {
                    throw new BizException("-1", "阿里云未知错误", false);
                }

            }
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return retData;
    }

    public static void main(String[] args) {
        NbMessage o = new NbMessage();
        SendTrigonalSmsReqDto req = new SendTrigonalSmsReqDto();

        o.sendTrigonalSms(req);
    }

    /**
     * code:receptionService
     * name:约定：位置标识
     * desc:undefined
     * gen by moon at 11/10/2023, 3:51:03 AM
     **/
    @Trace(operationName = "约定：位置标识")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementAcceptFieldRespDto implementAcceptField(ImplementAcceptFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementAcceptFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:约定：消息位置标识
     * desc:undefined
     * gen by moon at 11/12/2023, 9:52:50 PM
     **/
    @Trace(operationName = "约定：消息位置标识")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementTypeCodeFieldsAcceptRespDto implementTypeCodeFieldsAccept(ImplementTypeCodeFieldsAcceptReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementTypeCodeFieldsAcceptRespDto.class);

    }

    /**
     * code:additionOfTwoNum
     * name:M2计算两个数值相加（特殊方法）
     * desc:undefined
     * gen by moon at 12/12/2023, 5:02:51 AM
     **/
    @Trace(operationName = "M2计算两个数值相加（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public CalculateAdditionOfTwoNumsRespDto calculateAdditionOfTwoNums(CalculateAdditionOfTwoNumsReqDto reqDto) {
        CalculateAdditionOfTwoNumsRespDto retData = new CalculateAdditionOfTwoNumsRespDto();

        retData.setCalcResult(reqDto.getCalcPara1().doubleValue() + reqDto.getCalcPara2().doubleValue());
        return retData;
    }

    /**
     * code:receptionService
     * name:M2约定为否
     * desc:undefined
     * gen by moon at 12/19/2023, 6:51:29 PM
     **/
    @Trace(operationName = "M2约定为否")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementSmartSessionReceiveFieldInputRespDto implementSmartSessionReceiveFieldInput(ImplementSmartSessionReceiveFieldInputReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementSmartSessionReceiveFieldInputRespDto.class);
    }

    /**
     * code:sendSms
     * name:M2发送三方短信
     * desc:undefined
     * gen by moon at 12/20/2023, 9:15:30 PM
     **/
    @Trace(operationName = "M2发送三方短信")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public SendTrigonalSmsRespDto sendTrigonalSms(SendTrigonalSmsReqDto reqDto) {
        SendTrigonalSmsRespDto retData = new SendTrigonalSmsRespDto();
        IClientProfile profile = DefaultProfile.getProfile(reqDto.getSmsServeUrl(), reqDto.getAliyunAk(), reqDto.getAliyunSk());
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsResponse ret = null;
        try {
            // 构建参数
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(reqDto.getSmsReceiver());
            request.setSignName(reqDto.getSmsKey());
            request.setTemplateCode(reqDto.getSmsTemplateCode());
            JSONObject jo = new JSONObject();
            for (FieldsNameAndValueToOneDatasDto one : reqDto.getFieldsNameAndValueToOneDatasList()) {
                jo.put(one.getFieldName(), one.getFieldValue());
            }
            request.setTemplateParam(jo.toJSONString());
            request.setOutId(CommonFunctionHelper.getUid());
            ret = sendAliMsg(request, client);
            if (ret.getCode() != null && !ret.getCode().equals("OK")) {
                if (ret.getMessage() != null) {
                    throw new BizException("-1", ret.getMessage(), false);
                } else {
                    throw new BizException("-1", "阿里云未知错误", false);
                }

            }
        } catch (Exception e) {
            if (ret.getCode() != null && !ret.getCode().equals("OK")) {
                if (ret.getMessage() != null) {
                    throw new BizException("-1", ret.getMessage(), false);
                } else {
                    throw new BizException("-1", "阿里云未知错误", false);
                }

            }
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return retData;
    }

    /**
     * code:receptionService
     * name:M2执行接收数据集出参（特殊方法）
     * desc:undefined
     * gen by moon at 12/23/2023, 8:01:31 PM
     **/
    @Trace(operationName = "M2执行接收数据集出参（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementAcceptDataSetOutputRespDto implementAcceptDataSetOutput(ImplementAcceptDataSetOutputReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementAcceptDataSetOutputRespDto.class);
    }

    /**
     * code:publicFieldCache
     * name:M2执行业务组件公共字段推送内存（特殊方法）
     * desc:undefined
     * gen by moon at 1/17/2024, 12:20:50 AM
     **/
    @Trace(operationName = "M2执行业务组件公共字段推送内存（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementBizModuleAccessParameterFieldRespDto implementBizModuleAccessParameterField(ImplementBizModuleAccessParameterFieldReqDto reqDto) {
        BaseInfoDO domain = new BaseInfoDO();
        if (BaseInfoHolder.contextHolder.get() != null) {
            BeanUtil.copyProperties(BaseInfoHolder.contextHolder.get().getBaseInfo(), domain);
            BaseInfoHolder.contextHolder.remove();
        }
        if (reqDto.getSpaceId() != null) {
            domain.setSpecSpaceId(reqDto.getSpaceId());
        }

        if (reqDto.getCreateInductionId() != null) {
            domain.setSpecInductionRecordId(reqDto.getCreateInductionId());
        }

        if (reqDto.getAppId() != null) {
            domain.setSpecAppId(reqDto.getAppId());
        }

        CommonFunctionHelper.setBaseInfoToLocal(domain);
        return new ImplementBizModuleAccessParameterFieldRespDto();
    }
}

//手工接入方法

